﻿using System;
using System.Collections.Generic;
using System.Linq;
using SportsStore.Repository.Contexts;
using SportsStore.Repository.Interfaces;
using SportsStore.Model;
using Repository;

namespace SportsStore.Repository.Repositories
{
  using System.Data.Entity;
  using System.Data.Entity.Infrastructure;

  public class ProductRepository : BaseEfRepository<Product>, IProductRepository
  {
    public ProductRepository(string connectionString)
          : base(new SportsStoreDbContext(connectionString))
    {
    }

    public PagedResult<Product> GetProducts(int pageNumber, int numberOfItems, string category)
    {
      var products = Entities as DbSet<Product>;

      return GetPagedResultForQuery(products.Include("Category"), pageNumber, numberOfItems, category);
    }

    public Product GetProduct(int id)
    {
      return (from i in Entities.Include("Category")
              where i.Id == id
              select i).FirstOrDefault();
    }

    private PagedResult<Product> GetPagedResultForQuery(IQueryable<Product> products, int pageNumber, int numberOfItems, string category)
    {
      var result = new PagedResult<Product>
                     {
                       CurrentPage = pageNumber,
                       ItemsPerPage = numberOfItems,
                       TotalItems = category == null ?
                                  products.Count() :
                                  products.Count(c => c.Category.Name == category),
                       Results =
                         products.Where(p => category == null || p.Category.Name == category)
                                 .OrderBy(p => p.Id)
                                 .Skip((pageNumber - 1) * numberOfItems)
                                 .Take(numberOfItems)
                                 .ToList(),
                     };

      return result;
    }
  }
}
